/**
 * 首页展示
 */
import * as React from "react";
import { View, DeviceEventEmitter, Button } from "react-native";
import { SYSTEM_IP, NATIVE_GET_CALL } from "../../../core/common/Const";
import { BProps, BState, CalendarView, HeaderView ,BaseComponent} from "../../index";


const NativeInitModule = require('../../../core/modules/NativeInitModule');
const _ = require('lodash');
/**
 * 当前界面需要的状态state
 */
export interface State extends BState {
    hostIp:string,//当前界面获取到的IP地址
}
export default class MainViewComponent extends BaseComponent<BProps, State>{

    ipChangedListener:any;//ip发生变化通知RN
    nativeGetCallListener:any;//原生接口调用回传通知RN

  constructor(props: BProps) {
    super(props);
    //初始化ip
    this.state = {
      hostIp: "10.0.0.2",
    };
    this.start();
  }

  start() {
    this.ipChangedListener = DeviceEventEmitter.addListener(SYSTEM_IP, (ip) => {
      console.log("[RN接收到ip变化]" + JSON.stringify(ip));
      this.state = {
        // hostIp:ip[`${SYSTEM_IP}`],
        hostIp: "10.0.0.2",
      };
    });
    this.nativeGetCallListener = DeviceEventEmitter.addListener(
      NATIVE_GET_CALL,
      (result) => {
        console.log("[RN接收到原生接口请求数据]" + JSON.stringify(result));
        if (result && result.json) {
          console.log("[RN接收到原生接口请求数据]" + result.json.code);
        }
      }
    );
    this.init();
  }
  async init() {
    let map = await NativeInitModule.init();
    if (map) {
      this.state = {
        // hostIp:map[`${SYSTEM_IP}`],
        hostIp: "10.0.0.2",
      };
    }
    }

    UNSAFE_componentWillUnmount(){
        this.ipChangedListener && this.ipChangedListener.remove();
    }


    async getCall() {
        //get请求测试
        let url = `http://${this.state.hostIp}:8091/mobile/key?ip=${this.state.hostIp}&key=${this.state.hostIp}`;
        console.log("[获取的Url：]"+JSON.stringify(url));
        let data = await fetch(url); //获取后台数据
        data = await data.json();
        console.log("[获取的数据：]"+JSON.stringify(data));
    }

  async nativeGetCall() {
    //get请求测试
    let map = await NativeInitModule.get();
  }
  render() {
    let arry = ["a", "b", "c", "d"];
    return (
      <View style={{ flex: 1 }}>
        <HeaderView componentId={this.props.componentId} title={this.props.title} />
        <CalendarView componentId={this.props.componentId} />
        <Button
          title={"RN网络接口测试get" + JSON.stringify(_.chunk(arry, 3))}
          onPress={() => {
            //进行网络接口调用
            this.getCall();
          }}
        />
        <View style={{ height: 10 }} />
        <Button
          title={"RN网络接口测试post" + JSON.stringify(_.chunk(arry, 2))}
          onPress={() => {
            //进行网络接口调用
            this.postCall();
          }}
        />
        <View style={{ height: 10 }} />
        <Button
          title={"原生网络接口测试get"}
          onPress={() => {
            //进行网络接口调用
            this.nativeGetCall();
          }}
        />
      </View>
    );
  }
}